package org.example.common.websocket.holder;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.web.socket.WebSocketSession;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * WebSocketSession 用于保存当前所有在线的会话信息
 *
 * @author zendwang
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WebSocketSessionHolder {

    private static final Map<Long, Map<String, WebSocketSession>> USER_SESSION_MAP = new ConcurrentHashMap<>();
    private static final Map<String, List<Long>> USER_GROUP_MAP = new ConcurrentHashMap<>();
    private static final String DEFAULT_USER_GROUP="default_user_group";



    public static void addSession(String user_group,Long sessionKey, WebSocketSession session) {
        if(USER_SESSION_MAP.containsKey(sessionKey)){
            USER_SESSION_MAP.get(sessionKey).put(session.getId(),session);
        }else{
            Map<String, WebSocketSession> sessionMap=new HashMap();
            sessionMap.put(session.getId(),session);
            USER_SESSION_MAP.put(sessionKey, sessionMap);
        }
        if(USER_GROUP_MAP.containsKey(user_group)){
            USER_GROUP_MAP.get(user_group).add(sessionKey);
        }else{
            List list=new ArrayList();
            list.add(sessionKey);
            USER_GROUP_MAP.put(user_group, list);
        }
    }
    public static void addSession(Long sessionKey, WebSocketSession session) {
        WebSocketSessionHolder.addSession(DEFAULT_USER_GROUP,sessionKey,session);
    }


    public static void removeSession(String user_group,Long sessionKey, WebSocketSession session) {
        if (USER_SESSION_MAP.containsKey(sessionKey)) {
            if(USER_SESSION_MAP.get(sessionKey).size()>1){
                USER_SESSION_MAP.get(sessionKey).remove(session.getId());
            }else {
                USER_SESSION_MAP.remove(sessionKey);
            }
        }
        if(USER_GROUP_MAP.containsKey(user_group)){
            USER_GROUP_MAP.get(user_group).remove(sessionKey);
        }
    }

    public static void removeSession(Long sessionKey, WebSocketSession session) {
        WebSocketSessionHolder.removeSession(DEFAULT_USER_GROUP,sessionKey,session);
    }

    public static List<WebSocketSession> getSessions(Long sessionKey) {
        return USER_SESSION_MAP.get(sessionKey).values().stream().collect(Collectors.toList());
    }


    public static List<Long> getGroupSessions(String user_group) {
        return USER_GROUP_MAP.get(user_group).stream().collect(Collectors.toList());
    }

    public static Set<Long> getSessionsAll() {
        return USER_SESSION_MAP.keySet();
    }

    public static Boolean existSession(Long sessionKey) {
        return USER_SESSION_MAP.containsKey(sessionKey);
    }

}
